import os
from typing import Union


class RawFile(object):
    def __init__(self, path: str):
        self._path: str = path
        self._fd: int = 0

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.close()

    @staticmethod
    def open_file(path: str, mode: int):
        raw_file = RawFile(path)
        raw_file.open(mode)
        return raw_file

    def is_opened(self) -> bool:
        return self._fd != 0

    def open(self, mode: int) -> bool:
        self._fd = os.open(self._path, mode)
        return self.is_opened()

    def close(self):
        if not self.is_opened():
            os.close(self._fd)
        self._fd = 0

    def pos(self) -> int:
        if not self.is_opened():
            return -1

        return os.lseek(self._fd, 0, os.SEEK_CUR)

    def seek(self, pos: int) -> int:
        if not self.is_opened():
            return -1

        return os.lseek(self._fd, pos, os.SEEK_SET)

    def write(self, buff: bytes) -> int:
        if not self.is_opened():
            return -1

        return os.write(self._fd, buff)

    def read(self, length: int) -> Union[None, bytes]:
        if not self.is_opened():
            return None

        return os.read(self._fd, length)
